package com.betterjr.modules.risk.api.factory;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.betterjr.common.web.AbstarctRemoteApiInvoke;
import com.betterjr.common.web.AjaxObject;
import com.betterjr.common.web.AjaxRemoteApiParam;

@Service
public class RemoteApiInvokeFactory implements ApplicationContextAware, InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(RemoteApiInvokeFactory.class);

    private ApplicationContext applicationContext;

    private List<AbstarctRemoteApiInvoke> invokeList = new LinkedList<>();

    public String invokeApi(AjaxRemoteApiParam anParam) {

        logger.debug("RemoteApiInvokeFactory  invokeApi  参数：" + anParam);

        String error = "操作代码或请求参数不完整";

        if (anParam != null && StringUtils.isNoneBlank(anParam.getApiCode())) {
            for (AbstarctRemoteApiInvoke invoke : invokeList) {

                if (invoke.supportInvoke(anParam.getApiCode()) && invoke.checkParam(anParam.getParamMap())) {
                    try {
                        if (invoke.checkPre(anParam)) return invoke.saveOrFindInvoke(anParam);
                    }
                    catch (Exception e) {
                        error = "操作失败" + e.getMessage();
                    }

                }

            }
        }

        return AjaxObject.newError(error).toJson();

    }

    @Override
    public void afterPropertiesSet() throws Exception {

        String[] namesForType = applicationContext.getBeanNamesForType(AbstarctRemoteApiInvoke.class);
        for (String string : namesForType) {
            invokeList.add(applicationContext.getBean(string, AbstarctRemoteApiInvoke.class));
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;

    }

}
